package com.mediacloud.app.newsmodule.activity

import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.view.KeyEvent
import android.view.View
import android.view.animation.AnimationUtils
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.LinearLayout
import android.widget.TextView
import com.mediacloud.app.model.activity.BaseBackActivity
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.BrowseHisListAdapter
import com.mediacloud.app.newsmodule.model.HistoryBeanResult
import com.mediacloud.app.newsmodule.model.HistoryListParamsBean
import com.mediacloud.app.newsmodule.model.HistorySectionBean
import com.mediacloud.app.newsmodule.utils.HistoryInvoker
import com.mediacloud.app.user.model.UserInfo
import com.mediacloud.appcloud.project.gxapp.view.widget.CommonDialog
import kotlinx.android.synthetic.main.activity_browse_history_list.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * @author wy
 * @date 2020/2/10
 */
class BrowseHistoryListActivity : BaseBackActivity(), HistoryInvoker.GetHistoryListCallback, BrowseHisListAdapter.SelectedListener {

    companion object {

        @JvmStatic
        fun active(act: Activity) {
            act.startActivity<BrowseHistoryListActivity>()
        }
    }


    private val mAdapter: BrowseHisListAdapter by lazy {
        BrowseHisListAdapter(R.layout.layout_browse_his_title,R.layout.layout_browse_his_title_only_title,
            R.layout.layout_browse_his_header, mutableListOf())
    }
    private val invoker: HistoryInvoker by lazy { HistoryInvoker() }
    private val mParams: HistoryListParamsBean = HistoryListParamsBean()
    private val mDataList: MutableList<HistorySectionBean> = mutableListOf()
    private lateinit var tvClickClear: TextView
    private lateinit var tvDelete: TextView
    private lateinit var llBottomFuncation: LinearLayout

    override fun getLayoutResID(): Int = R.layout.activity_browse_history_list

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        initView()
        initData()
    }

    private fun initView() {
        setTitle(intent.getStringExtra("TITLE"))
        loadingView = findViewById(R.id.mLoadingView)
        showStateView(TYPE_LOADING, false)
        mMoreText.visibility = View.VISIBLE
        //btnDelete.textColor =delunEnableColor
        mTitlebar_MoreContainer.visibility = View.VISIBLE
        mTitlebar_More.visibility = View.GONE
        setMoreText("编辑")
        tvClickClear = findViewById(R.id.tv_click_clear)
        tvDelete = findViewById(R.id.tv_delete)
        llBottomFuncation = findViewById(R.id.ll_bottom_funcation)
        recyclerView.adapter = mAdapter
        mAdapter.selectedListener = this
        refreshLayout.setOnRefreshListener {
            initData()
        }
        refreshLayout.setOnLoadMoreListener {
            val userInfo = UserInfo.getUserInfo(this)
            mParams.page++
            invoker.getHistoryList(userInfo.userid, "", mParams, this)
        }
//        //设置空页面
//        var emptyView = LayoutInflater.from(this).inflate(R.layout.empty_new, null)
//        var imageView = emptyView.findViewById<ImageView>(R.id.imageView)
//        imageView.load(AppFactoryGlobalConfig.getAppServerConfigInfo(this).noContent, resources.getDrawable(R.drawable.no_content))
//        mAdapter.emptyView = emptyView
        tvClickClear.setOnClickListener {
            val userInfo = UserInfo.getUserInfo(this)
            //一键清空
            CommonDialog.Builder().builder(this)
                .setTitle("")
                .setMsg("清空所有历史吗？?")
                .setLeftButton(getString(R.string.quxiao))
                .setRightBotton(getString(R.string.queren), DialogInterface.OnClickListener { dialog, which -> //清空
                    invoker.clearHistoryList(userInfo.userid, this)
                })
                .create().show()

        }
        tvDelete.setOnClickListener {
            checkDeleteData()
        }

        keywordInput.setOnEditorActionListener(TextView.OnEditorActionListener { v, actionId, event ->
            val b = actionId == EditorInfo.IME_ACTION_SEARCH || event != null && event.keyCode == KeyEvent.KEYCODE_ENTER
            if (b) {
                mParams.page = 1
                invoker.getHistoryList(UserInfo.getUserInfo(this).userid, keywordInput.text.toString(), mParams, this)
                return@OnEditorActionListener true
            }
            false
        })
    }

    private fun initData() {
        val userInfo = UserInfo.getUserInfo(this)
        mParams.page = 1
        mParams.prePage = 20
        invoker.getHistoryList(userInfo.userid, "", mParams, this)
    }


    /**
     * 检查删除的数据
     */
    private fun checkDeleteData() {
        val list: MutableList<HistorySectionBean> = mAdapter.data.filter {
            it.t?.isSelect ?: false
        }.toMutableList()
        if (list.size > 0) {
            val ids = buildString {
                list.forEachIndexed { index, historySectionBean ->
                    append(historySectionBean.t.id)
                    if (index < list.size - 1) {
                        append(",")
                    }
                }
            }
            CommonDialog.Builder().builder(this)
                .setTitle("")
                .setMsg("确认删除${list.size}条浏览记录吗?")
                .setLeftButton(getString(R.string.quxiao))
                .setRightBotton("删除", DialogInterface.OnClickListener { dialog, which -> //清空
                    val userInfo = UserInfo.getUserInfo(this)
                    invoker.delHistoryList(userInfo.userid, ids, this)
                })
                .create().show()
        } else {
            toast("请选择需要删除的记录")
        }
    }

    /**
     * 编辑按钮点击
     */
    override fun moreClicked() {


        if (llBottomFuncation.visibility == View.VISIBLE) {
            mMoreText.text = "编辑"
            llBottomFuncation.visibility = View.GONE
            llBottomFuncation.animation = AnimationUtils.loadAnimation(this, R.anim.push_bottom_out)
            showListSelectView(false)
        } else {
            mMoreText.text = "取消"
            llBottomFuncation.visibility = View.VISIBLE
            llBottomFuncation.animation = AnimationUtils.loadAnimation(this, R.anim.push_bottom_in)
            showListSelectView(true)

            val list: MutableList<HistorySectionBean> = mAdapter.data.filter {
                it.t?.isSelect ?: false
            }.toMutableList()
            tvDelete.text = String.format(getString(R.string.delete_num), list.size)



        }

    }

    /**
     * 显示列表选择
     */
    private fun showListSelectView(isEdit: Boolean) {
        mDataList.forEach {
            if (!it.isHeader) {
                it.t?.isEdit = isEdit
                /* if (!isEdit) {
                     it.t?.isSelect = false
                 }*/
            }
        }
        //  mAdapter.notifyDataSetChanged()
        mAdapter.notifyItemRangeChanged(0,mAdapter.itemCount)
    }

    override fun onSuccess(data: HistoryBeanResult?) {
        closeStateView()
        refreshLayout.finishRefresh()
        refreshLayout.finishLoadMore()
        (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(this.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
        val list = data?.data?.meta ?: mutableListOf()
        if (list.size > 0) {
            val page = mParams.page
            val isEdit = mAdapter.data.any { it.t?.isEdit ?: false }
            if (page == 1) {    //第一页 清除数据
                tvDelete.text = String.format(getString(R.string.delete_num), 0)
                mAdapter.getSelectData()?.clear()
                mAdapter.notifyDataSetChanged()
                mDataList.clear()
            }
            list.forEach {
                if (!hasSameDay(mDataList, it.dateTypeString)) {    //设置标题
                    mDataList.add(HistorySectionBean(true, it.dateTypeString))
                }
                it.isEdit = isEdit
                mDataList.add(HistorySectionBean(it))
            }
            // refreshLayout.setEnableLoadMore(data?.haveMore() ?: false)
            mAdapter.setNewData(mDataList)
        } else {
            if (mParams.page == 1) {
                showStateView(TYPE_NO_CONTENT, false)
                mAdapter.setNewData(mutableListOf())
            }
            refreshLayout.setNoMoreData(true)
        }

    }

    /**
     * 是否已经有这个时间的标题了
     */
    private fun hasSameDay(list: MutableList<HistorySectionBean>, dateTitle: String): Boolean {
        return list.any { it.t?.dateTypeString == dateTitle }
    }

    override fun onError() {
        closeStateView()
        refreshLayout.finishRefresh(false)
        refreshLayout.finishLoadMore(false)
        showStateView(TYPE_NET_NOT_GIVE_FORCE, false)

    }


    override fun onDelSuccess() {
        initData()
        // moreClicked()
        toast("删除成功")
    }

    override fun onDelError() {
        toast("网络异常，请检查网络")
    }

    override fun onClearSuccess() {
        initData()
        toast("清除成功")
        // moreClicked()
    }

    override fun onClearError() {
        toast("网络异常，请检查网络")
    }

    override fun whenOfflineFinishPage(): Boolean {
        return true
    }

    override fun getContent_show_top_color(): String {
        mTitileBar.setBackgroundColor(Color.WHITE)
        return "#333333"
    }

    override fun getStatusBarColor(): Int {
        return Color.WHITE
    }

    override fun haveSelected(arrayList: ArrayList<Int>) {
        tvDelete.text = String.format(getString(R.string.delete_num), arrayList.size)
    }
}